#include "Common.hpp"
#include "InetAddr.hpp"


// ./tcpclient ip port
int main(int argc, char* argv[])
{
	if(argc != 3){
		std::cerr<<"Usage: ./tcpclient ip port"<<std::endl;
		exit(USAGE_ERR);
	}

	std::string ip = argv[1];
	uint16_t port = std::stoi(argv[2]);

	// 创建客户端套接字
	int clientfd = socket(AF_INET, SOCK_STREAM, 0);
	if(clientfd < 0){
		std::cerr<<"socket error"<<std::endl;
		exit(SOCKET_ERR);
	}

	InetAddr server(ip, port);
	int n = connect(clientfd, server.GetAddrPtr(), server.AddrLen());
	if(n < 0){
		std::cerr<<"connect error"<<std::endl;
		exit(CONNECT_ERR);
	}

	// 数据发送与接收
	while(true){
		// 发送数据
		std::cout<<"Please input #";
		std::string line;
		std::getline(std::cin, line);
		write(clientfd, line.c_str(), line.size());

		// 接收数据
		char buffer[1024];
		int size = read(clientfd, buffer, sizeof(buffer)-1);
		buffer[size] = 0;
		std::string echo = "server echo# ";
		echo += std::string(buffer);
		std::cout<<echo<<std::endl;
	}

	close(clientfd);
	LOG(LogLevel::INFO)<<"用户退出客户端";

	return 0;
}